package ms.platform.plan.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import ms.platform.plan.dto.FactoryDto;
import ms.platform.plan.dto.ModelDto;
import ms.platform.plan.dto.TargetDto;
import ms.platform.plan.model.ModelEntity;
import ms.platform.plan.model.ModelMeterPlan;
import ms.platform.plan.model.ModelPlan;
import ms.platform.plan.model.ModelProcessPlan;
import ms.platform.plan.service.BusModelService;
import ms.platform.plan.service.ModelPlanMeterService;
import ms.platform.system.controller.BaseController;
import ms.platform.system.service.ManufacturerService;
import ms.platform.util.DateUtil;
import ms.platform.util.ImportExcelUntil;
import ms.platform.util.PageUtils;
import ms.platform.util.StringUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/bus/plan/")
public class ModelController extends BaseController {

    @Autowired
    BusModelService busModelService;

    @Autowired
    ModelPlanMeterService modelPlanService;

    @Autowired
    private ManufacturerService manufacturerService;

    /**
     * 部品列表
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        try {
            //判断是否乱码
            //机种
            if (!StringUtil.isNullOrBlock(map.get("modelType"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("modelType")))) {
                    String fac = (String) map.get("modelType");
                    map.put("modelType",new String(fac.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            //部品番号
            if (!StringUtil.isNullOrBlock(map.get("modelCode"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("modelCode")))) {
                    String temp = (String) map.get("modelCode");
                    map.put("modelCode",new String(temp.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            //工程
            if (!StringUtil.isNullOrBlock(map.get("engineering"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("engineering")))) {
                    String temp = (String) map.get("engineering");
                    map.put("engineering",new String(temp.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //总条数
        map.put("count", busModelService.queryBusModelCount(map));
        List<ModelDto> list = busModelService.queryPageBusModelList(PageUtils.Page(request, map));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String newDate = df.format(new Date());
        for (ModelDto busModel : list) {
            if ("0".equals(busModel.getPlanStatus())) {
                busModel.setPlanStatusText("未提交");
            } else if ("1".equals(busModel.getPlanStatus())) {
                busModel.setPlanStatusText("已下发");
            } else {
                busModel.setPlanStatusText("已完成");
            }
            busModel.setLastReportTimeText(busModel.getLastReportTime());

            busModel.setPlanStartTimeText(DateUtil.getDateString(busModel.getPlanStartTime(), "YYYY-MM-dd"));
            busModel.setPlanEndTimeText(DateUtil.getDateString(busModel.getPlanEndTime(), "YYYY-MM-dd"));
            busModel.setAccStartTimeText(DateUtil.getDateString(busModel.getAccStartTime(), "YYYY-MM-dd"));
            busModel.setAccEndTimeText(DateUtil.getDateString(busModel.getAccEndTime(), "YYYY-MM-dd"));
        }
        List<FactoryDto> factoryList = busModelService.queryAllFactory("F");
        request.setAttribute("factoryList", factoryList);
        List<TargetDto> mTypeList = busModelService.queryAllmodelType();
        request.setAttribute("mTypeList", mTypeList);
        List<TargetDto> engList = busModelService.queryAllEngineering();
        request.setAttribute("engList", engList);
        request.setAttribute("list", list);
        PageUtils.calculate(map);
        request.getSession().setAttribute("queryPlanList", map);
        return "plan/list";
    }

    /**
     * 跳转部品新增页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/toAdd")
    public String toAdd(HttpServletRequest request) {
        List<FactoryDto> list = busModelService.queryAllFactory("F");
        request.setAttribute("factory", list);
        return "plan/add";
    }

    /**
     * 部品新增
     * @param admin
     * @param request
     * @return
     */
/*	@RequestMapping(value = "/saveBusModel", method = RequestMethod.POST)
    @ResponseBody
	public Object save(BusModel busModel, HttpServletRequest request){
		
		String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
		
		busModel.setInsertedBy(adminId);
		busModel.setInsertedAt(new Date());
		busModel.setUpdatedBy(adminId);
		busModel.setUpdatedAt(new Date());
		busModelService.saveBusModel(busModel);
		return returnSuccess("操作成功", busModel);
	}*/

    /**
     * 部品新增
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveBusModel", method = RequestMethod.POST)
    @ResponseBody
    public Object saveProcess(@RequestParam Map<String, Object> param, HttpServletRequest request) {
        try {
            String jsonData1 = param.get("bpdata") == null ? "" : param.get("bpdata").toString();
            List<ModelEntity> busModel = JSONArray.parseArray(jsonData1, ModelEntity.class);

            String jsonData2 = param.get("mjdata") == null ? "" : param.get("mjdata").toString();
            List<ModelPlan> modelPlan = JSONArray.parseArray(jsonData2, ModelPlan.class);
            String jsonData = param.get("arr") == null ? "" : param.get("arr").toString();
            jsonData = new String(jsonData.getBytes("UTF-8"), "UTF-8");
            List<ModelProcessPlan> list = JSONArray.parseArray(jsonData, ModelProcessPlan.class);

            String jsonData3 = param.get("jhdata") == null ? "" : param.get("jhdata").toString();
            List<ModelMeterPlan> modelMeterPlanList = JSONArray.parseArray(jsonData3, ModelMeterPlan.class);
            savePlan(busModel, modelPlan, list, modelMeterPlanList, request);

        } catch (Exception e) {
            e.printStackTrace();
            returnSuccess("系统错误", "");
        }

        return returnSuccess("操作成功", "");
    }

    private void savePlan(List<ModelEntity> busModel, List<ModelPlan> modelPlan, List<ModelProcessPlan> list, List<ModelMeterPlan> modelMeterPlanList, HttpServletRequest request) {
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        if (busModel.size() > 0) {
            busModel.get(0).setInsertedBy(adminId);
            busModel.get(0).setInsertedAt(new Date());
            busModel.get(0).setUpdatedBy(adminId);
            busModel.get(0).setUpdatedAt(new Date());
            busModelService.saveBusModel(busModel.get(0));
        }
        if (modelPlan.size() > 0) {
            modelPlan.get(0).setModelId(busModel.get(0).getId());
            modelPlan.get(0).setStatus("0");
            modelPlan.get(0).setReceiveFlag("0");
            modelPlan.get(0).setInsertedBy(adminId);
            modelPlan.get(0).setInsertedAt(new Date());
            modelPlan.get(0).setUpdatedBy(adminId);
            modelPlan.get(0).setUpdatedAt(new Date());
            modelPlan.get(0).setReportFreq(2);
            busModelService.saveBusModelPlan(modelPlan.get(0));

        }
        for (ModelProcessPlan modelProcessPlan : list) {
            if ("1".equals(modelProcessPlan.getOperation())) {
                modelProcessPlan.setAccStartTime(modelProcessPlan.getPlanStartTime());
                modelProcessPlan.setAccEndTime(modelProcessPlan.getPlanEndTime());
            }
            modelProcessPlan.setInsertedBy(adminId);
            modelProcessPlan.setInsertedAt(new Date());
            modelProcessPlan.setUpdatedBy(adminId);
            modelProcessPlan.setUpdatedAt(new Date());
            modelProcessPlan.setModelPlanId(modelPlan.get(0).getId());
        }
        busModelService.saveBusModelProcessPlan(list);

        if (modelMeterPlanList.size() > 0) {
            for (ModelMeterPlan modelMeterPlan : modelMeterPlanList) {
                modelMeterPlan.setModelPlanId(modelPlan.get(0).getId());
                modelMeterPlan.setModelId(busModel.get(0).getId());
                modelMeterPlan.setInsertedBy(adminId);
                modelMeterPlan.setInsertedAt(new Date());
                modelMeterPlan.setUpdatedBy(adminId);
                modelMeterPlan.setUpdatedAt(new Date());
                busModelService.saveBusModelMeterPlan(modelMeterPlan);
                //busModelService.saveBusMeterGiveRecord(modelMeterPlan);
            }
        }
    }

    @RequestMapping(value = "/improtExcel", method = {RequestMethod.POST})
    public String ImprotExcel(@RequestParam(value = "uploadFile") MultipartFile file, HttpServletRequest request) {
        String msg = "";
        String reason = "";
        List<ModelEntity> resultModel = new ArrayList<>();
        try {
            String name = file.getOriginalFilename();
            boolean is2003 = true;
            if (name != null) {
                if (ImportExcelUntil.isExcel2007(name)) {
                    is2003 = false;
                }
            }
            if (is2003) {
                HSSFSheet sheet = ImportExcelUntil.importExcelis2003(file);
                //获取 工序名
                List<String> codeName = new ArrayList<>();
                for (int i = 0; i <= 0; i++) {
                    HSSFRow xrow = sheet.getRow(i);
                    if (xrow != null) {
                        for (int index = 12; index < xrow.getPhysicalNumberOfCells(); index += 3) {
                            if (index >= 12) {
                                String val = ImportExcelUntil.getVal(xrow.getCell(index));
                                codeName.add(val);
                            }
                        }
                    }
                }
                //模板不对
                if (codeName.size() == 0) {
                    request.setAttribute("msgList", resultModel);
                    request.setAttribute("msg", "导入模板有误！请检查模板是否正确。");
                    return "plan/success";
                }
                //遍历行 从下标第一行开始（去除标题）
                this.isExcelis2003(sheet, resultModel, msg, reason,codeName,request);

            } else {
                XSSFSheet sheet = ImportExcelUntil.importExcelis2007(file);
                //获取 工序名
                List<String> codeName = new ArrayList<>();
                for (int i = 0; i <= 0; i++) {
                    XSSFRow xrow = sheet.getRow(i);
                    if (xrow != null) {
                        for (int index = 12; index < xrow.getPhysicalNumberOfCells(); index += 3) {
                            if (index >= 12) {
                                String val = ImportExcelUntil.getValx(xrow.getCell(index));
                                codeName.add(val);
                            }
                        }
                    }
                }
                //模板不对
                if (codeName.size() == 0) {
                    request.setAttribute("msgList", resultModel);
                    request.setAttribute("msg", "导入模板有误！请检查模板是否正确。");
                    return "plan/success";
                }
                this.isExcelis2007(sheet, resultModel, msg, reason,codeName,request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("msgList", resultModel);
        return "plan/success";
    }

    private void isExcelis2007(XSSFSheet sheet, List<ModelEntity> resultModel, String msg, String reason, List<String> codeName, HttpServletRequest request) {
        //遍历行 从下标第一行开始（去除标题）
        for (int i = 2; i <= sheet.getLastRowNum(); i++) {
            XSSFRow xrow = sheet.getRow(i);
            int resultNum = 0;//记录错误号  1，获取厂商名出错
            int planTotalTime = 0;//预计耗时总数
            if (xrow != null) {
                //装载
                String modelCode = "";
                List<ModelEntity> busModel = new ArrayList<>();
                List<ModelPlan> modelPlans = new ArrayList<>();
                List<ModelProcessPlan> modelProcessPlans = new ArrayList<>();
                List<ModelMeterPlan> modelMeterPlanList = new ArrayList<>();
                ModelEntity modelEntity = new ModelEntity();
                ModelPlan modelPlan = new ModelPlan();
                Date beginDate = new Date();
                Date endDatePlanEndTime = new Date();
                //获取总列数
                int allNum = xrow.getPhysicalNumberOfCells();
                for (int index = 0; index < allNum; index++) {
                    String val = ImportExcelUntil.getValx(xrow.getCell(index));
                    modelEntity.setStatus("1");
                    //1到11除了厚板为int 其他为string
                    if ((index >= 0 && index <= 3) || (index >= 5 && index <= 9)) {
                        xrow.getCell(index).setCellType(HSSFCell.CELL_TYPE_STRING);
                        val = ImportExcelUntil.getValx(xrow.getCell(index));
                    }
                    if (index == 0) {//部品番号
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 3;//部品番号为空
                            break;
                        }
                        modelEntity.setModelCode(val);
                        modelPlan.setModelCode(val);
                        modelCode = val;
                    }
//                    if (index == 1) {//工程
//                        if (StringUtil.isNullOrBlock(val)) {
//                            resultNum = 4;//工程为空
//                            break;
//                        }
//                        modelEntity.setEngineering(val);
//                    }
                    if (index == 1) {//机型
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 5;//机型为空
                            break;
                        }
                        modelEntity.setModelType(val);
                    }
                    if (index == 2) {//难易度
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 6;//难易度为空
                            break;
                        }
                        modelEntity.setModelLevel(val);
                    }
                    if (index == 3) {//材质
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 7;//材质为空
                            break;
                        }
                        modelEntity.setModelTexture(val);
                    }
                    if (index == 4) {//板厚
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 2;//板厚为空
                            break;
                        }
                        modelEntity.setModelPly(Float.valueOf(val));
                    }
                    if (index == 5) {//量产设备
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 8;//量产设备为空
                            break;
                        }
                        modelEntity.setModelBl(val);
                    }
                    if (index == 6) {//机床信息
                        modelEntity.setModelPr(val);
                    }
                    if (index == 7) {//所属客户
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 9;//所属客户为空
                            break;
                        }
                        modelEntity.setCustomer(val);
                    }
                    if (index == 8) {//设变号
                        modelEntity.setChangeNo(val);
                    }
                    if (index == 9) {//厂商
                        //根据名获取code
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 10;//厂商为空
                            break;
                        }
                        if (manufacturerService.getManufacturerName(val) != null) {
                            String code = manufacturerService.getManufacturerName(val).getOrgCode();
                            modelEntity.setFactory(val);
                            modelPlan.setFactory(code);
                        } else {
                            modelEntity.setFactory(val);
                            resultNum = 1;//厂家名有误
                            break;
                        }
                    }

                    if (index == 10) {//计划开始时间
                        if (xrow.getCell(index).getDateCellValue() == null) {
                            resultNum = 12;//计划开始时间有误
                            break;
                        }
                        beginDate = xrow.getCell(index).getDateCellValue();
                        modelPlan.setPlanStartTime(xrow.getCell(index).getDateCellValue());
                    }
                    if (index == 11) {//计划结束时间
//                                modelPlan.setPlanEndTime(xrow.getCell(index).getDateCellValue()); //获取 得到结束时间
                        modelPlan.setPlanEndTime(endDatePlanEndTime);//计算得到最后 结束时间
                    }
                    if (index >= 12) {//参考耗时（天）预计耗时（天）精度（%） 后面的每三个循环一次
                        int codename = 0;//工序名
                        double endDate = 0;//计划结束时间
                        boolean tempDate = true;//如果是第一次获取开始时间 否则获取累计开始时间
                        for (int x = index; x < allNum; x += 3) {
                            ModelProcessPlan modelProcessPlan = new ModelProcessPlan();
                            for (int code = 0; code < codeName.size(); code++) {
                                if (code == codename) {
                                    //工序名称
                                    modelProcessPlan.setProcessName(codeName.get(code));
                                    break;
                                }
                            }
                            if(!StringUtils.isNotEmpty(modelProcessPlan.getProcessName())){
                            	break;
                            }
                            //计划开始时间
                            Date start = new Date();
                            int endt = 0;
                            if (tempDate) {
                                start = beginDate;
                            } else {
                        		if (xrow.getCell(x + 1).getNumericCellValue() != 0) {
                                    //如果预计耗时不为0,下一天就需要+1
                                    start.setTime((long) endDate + 86400000);//重新赋值 做为新的开始时间
                                    endt = 86400000;
                                }else{
                                    start.setTime((long) endDate);//重新赋值 做为新的开始时间
                                }
                            }
                            modelProcessPlan.setPlanStartTime(start);
                            //计划结束时间 = 计划开始时间 + 预计耗时  累计下去 index+1=预计耗时（天）
                            endDate = xrow.getCell(x + 1).getNumericCellValue();
                            //将天转换成秒
                            endDate = endDate * 86400000 + start.getTime() - endt;//结束时间

                            modelProcessPlan.setPlanEndTime(new Date((long) endDate));
                            double target = xrow.getCell(x + 2).getNumericCellValue();
                            modelProcessPlan.setPlanTotalTime((int) xrow.getCell(x + 1).getNumericCellValue());//预计耗时
                            modelProcessPlan.setRefTime((int) xrow.getCell(x).getNumericCellValue());//参考耗时
                            modelProcessPlan.setTargetPre(String.valueOf(target));//精度
                            modelProcessPlan.setOperation("0");
                            modelProcessPlan.setModelCode(modelCode);//部品番号
                            modelProcessPlans.add(modelProcessPlan);
                            tempDate = false;
                            endDatePlanEndTime.setTime((long) endDate);
                            planTotalTime += xrow.getCell(x + 1).getNumericCellValue();
                            codename++;
                        }
                        break;
                    }
                }
                busModel.add(modelEntity);
                modelPlan.setPlanTotalTime(planTotalTime);//预计总耗时
                modelPlans.add(modelPlan);
                try {
                    if (resultNum == 1) {
                        msg = "导入失败";
                        reason = "厂家名称有误";
                    } else if (resultNum == 2) {
                        msg = "导入失败";
                        reason = "板厚为空";
                    } else if (resultNum == 3) {
                        msg = "导入失败";
                        reason = "部品番号为空";
                    } else if (resultNum == 5) {
                        msg = "导入失败";
                        reason = "机型为空";
                    } else if (resultNum == 6) {
                        msg = "导入失败";
                        reason = "难易度为空";
                    } else if (resultNum == 7) {
                        msg = "导入失败";
                        reason = "材质为空";
                    } else if (resultNum == 8) {
                        msg = "导入失败";
                        reason = "量产设备为空";
                    } else if (resultNum == 9) {
                        msg = "导入失败";
                        reason = "所属客户为空";
                    } else if (resultNum == 10) {
                        msg = "导入失败";
                        reason = "厂商为空";
                    } else if (resultNum == 12) {
                        msg = "导入失败";
                        reason = "计划开始时间为空";
                    } else {
                        Map<String, Object> map = new HashMap<>();
                        if (busModel.size() > 0) {
                            map.put("engineering", modelEntity.getEngineering());
                            map.put("modelCode", modelEntity.getModelCode());
                        }
                        boolean flag = busModelService.queryModelInfoByCodeAndEngineer(map);
                        if (flag) {
                            reason = "重复录入";
                            msg = "导入失败";
                        } else {
                            savePlan(busModel, modelPlans, modelProcessPlans, modelMeterPlanList, request);//批量插入数据库
                            msg = "导入成功";
                            reason = "";
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    msg = "导入失败";
                    reason = "数据错误";
                }
                modelEntity.setResultImport(msg);
                modelEntity.setReason(reason);
                resultModel.add(modelEntity);
            }
        }
    }

    private void isExcelis2003(HSSFSheet sheet, List<ModelEntity> resultModel, String msg, String reason, List<String> codeName, HttpServletRequest request) {
        for (int i = 2; i <= sheet.getLastRowNum(); i++) {
            HSSFRow xrow = sheet.getRow(i);
            int resultNum = 0;//记录错误号  1，获取厂商名出错
            int planTotalTime = 0;//预计耗时总数
            if (xrow != null) {
                //装载
                String modelCode = "";
                List<ModelPlan> modelPlans = new ArrayList<>();
                List<ModelProcessPlan> modelProcessPlans = new ArrayList<>();
                List<ModelMeterPlan> modelMeterPlanList = new ArrayList<>();
                List<ModelEntity> busModel = new ArrayList<>();
                ModelEntity modelEntity = new ModelEntity();
                ModelPlan modelPlan = new ModelPlan();
                Date beginDate = new Date();
                Date endDatePlanEndTime = new Date();
                //获取总列数
                int allNum = xrow.getPhysicalNumberOfCells();
                for (int index = 0; index < allNum; index++) {
                    String val = ImportExcelUntil.getVal(xrow.getCell(index));
                    modelEntity.setStatus("1");
                    //1到9除了厚板为int 其他为string
                    if ((index >= 0 && index <= 3) || (index >= 5 && index <= 9)) {
                        xrow.getCell(index).setCellType(HSSFCell.CELL_TYPE_STRING);
                        val = ImportExcelUntil.getVal(xrow.getCell(index));
                    }
                    if (index == 0) {//部品番号
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 3;//部品番号为空
                            break;
                        }
                        modelCode = val;
                        modelEntity.setModelCode(val);
                        modelPlan.setModelCode(val);
                    }
//                    if (index == 1) {//工程 去掉工程 2018-05-29
//                        if (StringUtil.isNullOrBlock(val)) {
//                            resultNum = 4;//工程为空
//                            break;
//                        }
//                        modelEntity.setEngineering(val);
//                    }
                    if (index == 1) {//机型
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 5;//机型为空
                            break;
                        }
                        modelEntity.setModelType(val);
                    }
                    if (index == 2) {//难易度
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 6;//难易度为空
                            break;
                        }
                        modelEntity.setModelLevel(val);
                    }
                    if (index == 3) {//材质
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 7;//材质为空
                            break;
                        }
                        modelEntity.setModelTexture(val);
                    }
                    if (index == 4) {//板厚
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 2;//板厚为空
                            break;
                        }
                        modelEntity.setModelPly(Float.valueOf(val));
                    }
                    if (index == 5) {//量产设备
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 8;//量产设备为空
                            break;
                        }
                        modelEntity.setModelBl(val);
                    }
                    if (index == 6) {//机床信息
                        modelEntity.setModelPr(val);
                    }
                    if (index == 7) {//所属客户
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 9;//所属客户为空
                            break;
                        }
                        modelEntity.setCustomer(val);
                    }
                    if (index == 8) {//设变号
                        modelEntity.setChangeNo(val);
                    }
//                    if (index == 11) {//次型
//                        if ("一次型".equals(val)) {
//                            modelPlan.setType("1");
//                        } else {
//                            modelPlan.setType("2");
//                        }
//                        if (StringUtil.isNullOrBlock(val)) {
//                            resultNum = 11;//次型为空
//                            break;
//                        }
//                    }
                    if (index == 9) {//厂商
                        //根据名获取code
                        if (StringUtil.isNullOrBlock(val)) {
                            resultNum = 10;//厂商为空
                            break;
                        }
                        if (manufacturerService.getManufacturerName(val) != null) {
                            String code = manufacturerService.getManufacturerName(val).getOrgCode();
                            modelPlan.setFactory(code);
                            modelEntity.setFactory(val);
                        } else {
                            resultNum = 1;//厂家名有误
                            modelEntity.setFactory(val);
                            break;
                        }
                    }
                    if (index == 10) {//计划开始时间
                        if (xrow.getCell(index).getDateCellValue() == null) {
                            resultNum = 12;//计划开始时间有误
                            break;
                        }
                        beginDate = xrow.getCell(index).getDateCellValue();
                        modelPlan.setPlanStartTime(xrow.getCell(index).getDateCellValue());
                    }
                    if (index == 11) {//计划结束时间
//                                modelPlan.setPlanEndTime(xrow.getCell(index).getDateCellValue()); //获取 得到结束时间
                        modelPlan.setPlanEndTime(endDatePlanEndTime);//计算得到最后 结束时间
                    }
                    if (index >= 12) {//参考耗时（天）预计耗时（天）精度（%） 后面的每三个循环一次
                        double endDate = 0;//计划结束时间
                        int codename = 0;//工序名
                        boolean tempDate = true;//如果是第一次获取开始时间 否则获取累计开始时间
                        for (int x = index; x < allNum; x += 3) {
                            ModelProcessPlan modelProcessPlan = new ModelProcessPlan();
                            for (int code = 0; code < codeName.size(); code++) {
                                if (code == codename) {
                                    //工序名称
                                    modelProcessPlan.setProcessName(codeName.get(code));
                                    break;
                                }
                            }
                            //计划开始时间
                            Date start = new Date();
                            int endt = 0;
                            if (tempDate) {
                                start = beginDate;
                            } else {
                                if (xrow.getCell(x + 1).getNumericCellValue() != 0) {
                                    //如果预计耗时不为0,下一天就需要+1
                                    start.setTime((long) endDate + 86400000);//重新赋值 做为新的开始时间
                                    endt = 86400000;
                                }else{
                                    start.setTime((long) endDate);//重新赋值 做为新的开始时间
                                }
                            }
                            modelProcessPlan.setPlanStartTime(start);
                            //计划结束时间 = 计划开始时间 + 预计耗时  累计下去 index+1=预计耗时（天）
                            endDate = xrow.getCell(x + 1).getNumericCellValue();
                            //将天转换成秒
                            endDate = endDate * 86400000 + start.getTime() - endt;//结束时间
                            modelProcessPlan.setPlanEndTime(new Date((long) endDate));
                            double target = xrow.getCell(x + 2).getNumericCellValue();
                            modelProcessPlan.setPlanTotalTime((int) xrow.getCell(x + 1).getNumericCellValue());//预计耗时
                            modelProcessPlan.setRefTime((int) xrow.getCell(x).getNumericCellValue());//参考耗时
                            modelProcessPlan.setOperation("0");
                            modelProcessPlan.setModelCode(modelCode);//部品番号
                            modelProcessPlan.setTargetPre(String.valueOf(target));//精度
                            modelProcessPlans.add(modelProcessPlan);
                            tempDate = false;
                            endDatePlanEndTime.setTime((long) endDate);
                            planTotalTime += xrow.getCell(x + 1).getNumericCellValue();
                            codename++;
                        }
                        break;
                    }
                }
                busModel.add(modelEntity);
                modelPlan.setPlanTotalTime(planTotalTime);//预计总耗时
                modelPlans.add(modelPlan);
                try {
                    if (resultNum == 1) {
                        msg = "导入失败";
                        reason = "厂家名称有误";
                    } else if (resultNum == 2) {
                        msg = "导入失败";
                        reason = "板厚为空";
                    } else if (resultNum == 3) {
                        msg = "导入失败";
                        reason = "部品番号为空";
                    } else if (resultNum == 5) {
                        msg = "导入失败";
                        reason = "机型为空";
                    } else if (resultNum == 6) {
                        msg = "导入失败";
                        reason = "难易度为空";
                    } else if (resultNum == 7) {
                        msg = "导入失败";
                        reason = "材质为空";
                    } else if (resultNum == 8) {
                        msg = "导入失败";
                        reason = "量产设备为空";
                    } else if (resultNum == 9) {
                        msg = "导入失败";
                        reason = "所属客户为空";
                    } else if (resultNum == 10) {
                        msg = "导入失败";
                        reason = "厂商为空";
                    } else if (resultNum == 12) {
                        msg = "导入失败";
                        reason = "计划开始时间为空";
                    } else {
                        Map<String, Object> map = new HashMap<>();
                        if (busModel.size() > 0) {
                            map.put("modelCode", modelEntity.getModelCode());
                            map.put("engineering", modelEntity.getEngineering());
                        }
                        boolean flag = busModelService.queryModelInfoByCodeAndEngineer(map);
                        if (flag) {
                            msg = "导入失败";
                            reason = "重复录入";
                        } else {
                            savePlan(busModel, modelPlans, modelProcessPlans, modelMeterPlanList, request);//批量插入数据库
                            reason = "";
                            msg = "导入成功";
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    msg = "导入失败";
                    reason = "数据错误";
                }
                modelEntity.setResultImport(msg);
                modelEntity.setReason(reason);
                resultModel.add(modelEntity);
            }
        }
    }

    /**
     * 跳转部品修改页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/toEdit")
    public String toEdit(@RequestParam Map<String, String> param, HttpServletRequest request) {
        Integer id = Integer.parseInt(param.get("mapId"));
        request.setAttribute("map", param);
        if (id != null) {
            ModelDto model = busModelService.queryBusModelById(id);
            model.setPlanStartTimeText(DateUtil.getDateString(model.getPlanStartTime(), "YYYY-MM-dd"));
            model.setPlanEndTimeText(DateUtil.getDateString(model.getPlanEndTime(), "YYYY-MM-dd"));
            request.setAttribute("model", model);

            if (model.getModelPlanId() != null) {
                List<ModelProcessPlan> process = busModelService.queryBusModelProcessById(model.getModelPlanId());
                for (ModelProcessPlan modelProcessPlan : process) {
                    modelProcessPlan.setPlanStartTimeText(DateUtil.getDateString(modelProcessPlan.getPlanStartTime(), "YYYY-MM-dd"));
                    modelProcessPlan.setPlanEndTimeText(DateUtil.getDateString(modelProcessPlan.getPlanEndTime(), "YYYY-MM-dd"));
                }
                request.setAttribute("process", process);
            }
            List<ModelMeterPlan> meter = busModelService.queryBusModelMeterById(id);
            for (ModelMeterPlan modelMeterPlan : meter) {
                modelMeterPlan.setGiveTimeText(DateUtil.getDateString(modelMeterPlan.getGiveTime(), "YYYY-MM-dd"));
            }
            request.setAttribute("meter", meter);
        }
        List<FactoryDto> list = busModelService.queryAllFactory("F");
        request.setAttribute("factory", list);

        return "plan/edit";
    }

    /**
     * 跳转详情页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/toView")
    public String toView(@RequestParam Map<String, String> param, HttpServletRequest request) {
        Integer id = Integer.parseInt(param.get("mapId"));
        request.setAttribute("map", param);
        if (id != null) {
            ModelDto model = busModelService.queryBusModelById(id);
            model.setPlanStartTimeText(DateUtil.getDateString(model.getPlanStartTime(), "YYYY-MM-dd"));
            model.setPlanEndTimeText(DateUtil.getDateString(model.getPlanEndTime(), "YYYY-MM-dd"));
            request.setAttribute("model", model);

            if (model.getModelPlanId() != null) {
                List<ModelProcessPlan> process = busModelService.queryBusModelProcessById(model.getModelPlanId());
                for (ModelProcessPlan modelProcessPlan : process) {
                    modelProcessPlan.setPlanStartTimeText(DateUtil.getDateString(modelProcessPlan.getPlanStartTime(), "YYYY-MM-dd"));
                    modelProcessPlan.setPlanEndTimeText(DateUtil.getDateString(modelProcessPlan.getPlanEndTime(), "YYYY-MM-dd"));
                }
                request.setAttribute("process", process);
            }
            List<ModelMeterPlan> meter = busModelService.queryBusModelMeterById(id);
            for (ModelMeterPlan modelMeterPlan : meter) {
                modelMeterPlan.setGiveTimeText(DateUtil.getDateString(modelMeterPlan.getGiveTime(), "YYYY-MM-dd"));
            }
            request.setAttribute("meter", meter);
        }
        List<FactoryDto> list = busModelService.queryAllFactory("F");
        request.setAttribute("factory", list);
        return "plan/viewModel";
    }

    /**
     * 根据id查询材料信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryModelMeterById", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;"})
    @ResponseBody
    public Object queryMeter(@RequestParam Integer id, HttpServletRequest request) {
        ModelMeterPlan meter = busModelService.queryModelMeterById(id);
        meter.setGiveTimeText(DateUtil.getDateString(meter.getGiveTime(), "YYYY-MM-dd"));
        return JSONObject.toJSONString(meter);
    }

    /**
     * 根据id修改材料信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateModelMeterById", method = RequestMethod.POST)
    @ResponseBody
    public Object updateMeter(@RequestParam Map<String, Object> param, HttpServletRequest request) {
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        String jsonData = param.get("meterData") == null ? "" : param.get("meterData").toString();
        List<ModelMeterPlan> meter = JSONArray.parseArray(jsonData, ModelMeterPlan.class);
        for (ModelMeterPlan modelMeterPlan : meter) {
            if (null != modelMeterPlan.getId()) {
                modelMeterPlan.setUpdatedBy(adminId);
                busModelService.updateModelMeterById(modelMeterPlan);
            } else {
                modelMeterPlan.setInsertedBy(adminId);
                modelMeterPlan.setInsertedAt(new Date());
                modelMeterPlan.setUpdatedBy(adminId);
                modelMeterPlan.setUpdatedAt(new Date());
                busModelService.saveBusModelMeterPlan(modelMeterPlan);
            }
        }
        return returnSuccess("操作成功", meter);
    }

    /**
     * 根据id修改部品信息
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/updateBusModel", method = RequestMethod.POST)
    @ResponseBody
    public Object updateModel(@RequestParam Map<String, Object> param, HttpServletRequest request) throws UnsupportedEncodingException {
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        String jsonData = param.get("modelData") == null ? "" : param.get("modelData").toString();
        List<ModelEntity> model = JSONArray.parseArray(jsonData, ModelEntity.class);
        if (model.size() > 0) {
            model.get(0).setUpdatedBy(adminId);
            busModelService.updateModelById(model.get(0));
        }
        String jsonData1 = param.get("mjdata") == null ? "" : param.get("mjdata").toString();
        List<ModelPlan> plan = JSONArray.parseArray(jsonData1, ModelPlan.class);
        if (plan.size() > 0) {
            plan.get(0).setUpdatedBy(adminId);
            busModelService.updateBusModelPlan(plan.get(0));
        }
        String jsonData2 = param.get("arr") == null ? "" : param.get("arr").toString();
        jsonData2 = new String(jsonData2.getBytes("UTF-8"), "UTF-8");
        List<ModelProcessPlan> list = JSONArray.parseArray(jsonData2, ModelProcessPlan.class);
        for (ModelProcessPlan modelProcessPlan : list) {
            if (null != modelProcessPlan.getId()) {
                if (modelProcessPlan.getOperation().equals("1")) {
                    modelProcessPlan.setAccStartTime(modelProcessPlan.getPlanStartTime());
                    modelProcessPlan.setAccEndTime(modelProcessPlan.getPlanEndTime());
                }
                modelProcessPlan.setUpdatedBy(adminId);
                busModelService.updateBusModelProcessById(modelProcessPlan);
            } else {
                //新增工序
                modelProcessPlan.setInsertedBy(adminId);
                modelProcessPlan.setInsertedAt(new Date());
                modelProcessPlan.setUpdatedBy(adminId);
                modelProcessPlan.setUpdatedAt(new Date());
                modelProcessPlan.setModelPlanId(plan.get(0).getId());
            }
        }
        if (null != list && list.size() > 0) {
            if (null != list.get(0).getId()) {

            } else {
                //删除之前的工序
                busModelService.deleteProcessPlan(plan.get(0).getId());
                //新增工序
                busModelService.saveBusModelProcessPlan(list);
            }
        }
        return returnSuccess("操作成功", model);
    }

    /**
     * 根据id修改部品状态
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/updateBusModelStatus", method = RequestMethod.POST)
    @ResponseBody
    public Object updateModelStatus(@RequestParam Map<String, Object> param, HttpServletRequest request) throws UnsupportedEncodingException {
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        String jsonData = param.get("arr") == null ? "" : param.get("arr").toString();
        List<ModelEntity> model = JSONArray.parseArray(jsonData, ModelEntity.class);
        if (model.size() > 0) {
            model.get(0).setUpdatedBy(adminId);
            busModelService.updateModelStatusById(model.get(0));
        }
        return returnSuccess("操作成功", model);
    }

    /**
     * 计划下发
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/effective", method = RequestMethod.POST)
    @ResponseBody
    public Object effective(@RequestParam Map<String, Object> param, HttpServletRequest request) throws UnsupportedEncodingException {
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        String jsonData = param.get("arr") == null ? "" : param.get("arr").toString();
        List<ModelPlan> model = JSONArray.parseArray(jsonData, ModelPlan.class);
        if (model.size() > 0) {
            model.get(0).setUpdatedBy(adminId);
            modelPlanService.updateModelPlanStatusForEffective(model.get(0));
        }
        return returnSuccess("操作成功", model);
    }

    /**
     * 根据id修改计划状态
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/updateBusModelPlanStatus", method = RequestMethod.POST)
    @ResponseBody
    public Object updateModelPlanStatus(@RequestParam Map<String, Object> param, HttpServletRequest request) throws UnsupportedEncodingException {
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        String jsonData = param.get("arr") == null ? "" : param.get("arr").toString();
        List<ModelPlan> model = JSONArray.parseArray(jsonData, ModelPlan.class);
        if (model.size() > 0) {
            model.get(0).setUpdatedBy(adminId);
            modelPlanService.updateModelPlanStatusById(model.get(0));
        }
        return returnSuccess("操作成功", model);
    }

    /**
     * 根据id删除材料信息
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/deleteModelMeter", method = RequestMethod.POST)
    @ResponseBody
    public Object deleteModelMeter(@RequestParam Integer id, HttpServletRequest request) {
        String msg = "操作成功";
        if (id != null) {
            busModelService.deleteModelPlanMeterById(id);
        } else {
            msg = "操作失败";
        }
        return returnSuccess(msg, id);
    }

    /**
     * 根据id删除材料信息
     * @param admin
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     *//*
    @RequestMapping(value = "/queryAllFactory", method = RequestMethod.POST)
	@ResponseBody
	public Object queryAllFactory(HttpServletRequest request){
		List<FactoryDto> list = busModelService.queryAllFactory("F");
		return returnSuccess("操作成功",list);
	}*/

    /**
     * 跳转材料新增页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/toMeter")
    public String toAdd(String modelCode, HttpServletRequest request) {
        String code = "";
        try {
            code = new String(modelCode.getBytes("ISO-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        request.setAttribute("modelCode", code);
        return "meter/add";
    }

    /**
     * 根据番号和工程判断数据是否存在
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/checkRepeat", method = RequestMethod.POST)
    @ResponseBody
    public Object checkRepeat(@RequestParam Map<String, Object> param, HttpServletRequest request) {
        String jsonData1 = param.get("bpdata") == null ? "" : param.get("bpdata").toString();
        List<ModelEntity> busModel = JSONArray.parseArray(jsonData1, ModelEntity.class);
        Map<String, Object> map = new HashMap<String, Object>();
        if (busModel.size() > 0) {
            map.put("modelCode", busModel.get(0).getModelCode());
            //map.put("engineering", busModel.get(0).getEngineering());
        }
        boolean flag = busModelService.queryModelInfoByCodeAndEngineer(map);
        return returnSuccess("重复录入", flag);
    }

    /**
     * 获取工序模板
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/getProcessTemp", method = RequestMethod.POST)
    @ResponseBody
    public Object getProcessTemp(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        List<ModelProcessPlan> modelProcessPlan = new ArrayList<ModelProcessPlan>();
        if (map.size() > 0) {
            modelProcessPlan = busModelService.getProcessTemp(map);
        }
        return returnSuccess("", modelProcessPlan);
    }
}
